﻿using System;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;


//Renamed namespace CssFriendly to Enterprise.Adapters because it's not compatible with CssFriendly anymore  
namespace Enterprise.Adapters
{
    /// <summary>
    /// Produces a nice indented ul li menu with cssclass for selecteditem and selectedlevel
    /// </summary>
    public class MenuAdapter : System.Web.UI.WebControls.Adapters.MenuAdapter
    {
        public MenuAdapter(){}

        protected override void OnInit(EventArgs e){ base.OnInit(e);}
        protected override void RenderBeginTag(HtmlTextWriter writer){}
        protected override void RenderEndTag(HtmlTextWriter writer){}

        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.Indent++;
            BuildItems(Control.Items, true, writer);
            writer.Indent--;
            writer.WriteLine();
        }


        /// <summary>
        /// Build items
        /// </summary>
        /// <param name="items"></param>
        /// <param name="isRoot"></param>
        /// <param name="writer"></param>
        private void BuildItems(MenuItemCollection items, bool isRoot, HtmlTextWriter writer)
        {
            if (items.Count > 0)
            {
                writer.WriteLine();
                writer.WriteBeginTag("ul");

                if (isRoot)
                    writer.WriteAttribute("class", this.Control.ID);
                
                writer.Write(HtmlTextWriter.TagRightChar);
                writer.Indent++;

                foreach (MenuItem item in items)
                {
                    SiteMapNode itm = FindNode(item);
                    if (!IsHidden(itm))
                        BuildItem(item, writer);
                }
                
                writer.Indent--;
                writer.WriteLine();
                writer.WriteEndTag("ul");
            }
        }


        /// <summary>
        /// Find a node in same path.
        /// In this way we can alter any level of nodes and select the parent node if a subitem is selected.
        /// Very handy when using a topmenu with a submenu and want to select the menu above.
        /// </summary>
        /// <param name="node">The node to find the current node from.</param>
        /// <returns>True when found the node</returns>
        private bool IsInPath(SiteMapNode node) 
        {
            foreach (SiteMapNode child in node.ChildNodes)
            {
                if (child.Equals(SiteMap.CurrentNode))
                    return true;
                else
                    IsInPath(child); //Iterate until it's found.
            }
            return false;
        }



        /// <summary>
        /// Compares url's from node and sitemapnode and returns the found node.
        /// </summary>
        /// <param name="node">The node to compare</param>
        /// <returns>The found SiteMapNode</returns>
        private SiteMapNode FindNode(MenuItem node)
        {
            foreach(SiteMapNode tmpNode in SiteMap.RootNode.GetAllNodes())
            {
                if (tmpNode.Url.Equals(node.NavigateUrl))
                    return tmpNode;
            }
            return null; //Never happends
        }



        /// <summary>
        /// SiteMapNode that has attribute hidden="false" shouldn't show up in menu.
        /// </summary>
        /// <param name="node">SiteMapNode to check</param>
        /// <returns>True if node is hidden</returns>
        private bool IsHidden(SiteMapNode node)
        {
            if (Page.User.IsInRole(Roles.Administrators.ToString()))
                return false;

            if (node["Hidden"] != null)
            {
                if (Convert.ToString(node["Hidden"]).ToLower() == "true")
                    return true;
            }
            return false;
        }


        /// <summary>
        /// Moved to SqlSiteMapProvider
        /// Ensure that this node is active av viewable by public visitors. 
        /// </summary>
        /// <param name="node"></param>
        /// <returns>If node is active</returns>
        private bool IsActive(SiteMapNode node)
        {
            if (Page.User.IsInRole(Roles.Administrators.ToString()))
                return true;

            if (node["Active"] != null)
            {
                if (Convert.ToString(node["Active"]).ToLower() == "true")
                    return true;
            }
            return false;
        }

      
        /// <summary>
        /// Build's the menuitem and create css for selected levels
        /// </summary>
        /// <param name="item"></param>
        /// <param name="writer"></param>
        private void BuildItem(MenuItem item, HtmlTextWriter writer)
        {
            Menu menu = Control as Menu;
            if ((menu != null) && (item != null) && (writer != null))
            {
                writer.WriteLine();
                writer.WriteBeginTag("li");

                //Find root node for the current node(In level zero)
                if ( item.Depth == 0 && IsInPath( FindNode(item) ) )
                    writer.WriteAttribute("class", "selectedlevel");

                try
                {
                    string url = item.NavigateUrl;
                    if (SiteMap.CurrentNode.Url.Equals(url))
                        writer.WriteAttribute("class", "selected");
                }
                catch { }
                
                writer.Write(HtmlTextWriter.TagRightChar);
                writer.Indent++;
                writer.WriteLine();

                if (item.NavigateUrl.Length > 0)
                {
                    writer.WriteBeginTag("a");
                    writer.WriteAttribute("href", Page.ResolveUrl(item.NavigateUrl));

                    if (item.Target.Length > 0)
                    {
                        writer.WriteAttribute("target", item.Target);
                    }
                    if (item.ToolTip.Length > 0)
                    {
                        writer.WriteAttribute("title", item.ToolTip);
                    }
                    else if (menu.ToolTip.Length > 0)
                    {
                        writer.WriteAttribute("title", menu.ToolTip);
                    }

                    writer.Write(HtmlTextWriter.TagRightChar);
                    writer.Indent++;
                    writer.WriteLine();

                    writer.WriteBeginTag("span");
                    writer.Write(HtmlTextWriter.TagRightChar);

                }
                else
                {
                    writer.WriteBeginTag("span");
                    writer.Write(HtmlTextWriter.TagRightChar);

                    writer.Indent++;
                    writer.WriteLine();
                }

                if (item.ImageUrl.Length > 0)
                {
                    writer.WriteBeginTag("img");
                    writer.WriteAttribute("src", Page.ResolveUrl(item.ImageUrl));
                    writer.WriteAttribute("alt", item.ToolTip.Length > 0 ? item.ToolTip : (menu.ToolTip.Length > 0 ? menu.ToolTip : item.Text));
                    writer.Write(HtmlTextWriter.SelfClosingTagEnd);
                }

                writer.Write(item.Text);
                writer.WriteEndTag("span");

                if (item.NavigateUrl.Length > 0)
                {
                    writer.Indent--;
                    writer.WriteLine();
                    writer.WriteEndTag("a");
                }
                else
                {
                    writer.Indent--;
                    writer.WriteLine();

                }

                if ((item.ChildItems != null) && (item.ChildItems.Count > 0))
                {
                    BuildItems(item.ChildItems, false, writer);
                }

                writer.Indent--;
                writer.WriteLine();
                writer.WriteEndTag("li");
            }
        }
    }
}
